package com.ckzp.plugins.layui;

import com.ckzp.core.json.Jmode;
import com.ckzp.core.json.JsonUtil;
import com.jfinal.plugin.activerecord.Model;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 51594 on 2022/7/28.
 */
public class LayuiData {

    //0成功
    public int code = 0;

    /**
     * 提示信息
     */
    public String msg = "";

    /**
     * 反回数据总量
     */
    public int count = 0;

    /**
     * 数据明细
     */
    public List<Model> data = new ArrayList();
    /**
     * 扩展数据信息
     */
    public Jmode ext = Jmode.n();

    /**
     * @return
     */
    public static LayuiData newData() {
        return new LayuiData();
    }

    /**
     * @return
     */
    public static LayuiData n() {
        return new LayuiData();
    }


    public int getCode() {
        return code;
    }

    public LayuiData setCode(int code) {
        this.code = code;
        return this;
    }


    public LayuiData setExt(Jmode jm) {
        this.ext = jm;
        return this;
    }

    public String getMsg() {
        return msg;
    }

    public LayuiData setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public int getCount() {
        return count;
    }

    public LayuiData setCount(int count) {
        this.count = count;
        return this;
    }

    public List<Model> getData() {
        return data;
    }

    public LayuiData setData(List data) {
        this.data = data;
        return this;
    }

    public Jmode getExt() {
        return ext;
    }

    /**
     * 配置默认值，一般不用，影响编辑和导出数据
     *
     * @param def
     * @return
     */
    public LayuiData setDefault(String def) {
        if (def != null && def.length() > 0) {
            for (Model o : data) {
                if (o != null) {
                    String[] it = o._getAttrNames();
                    for (String key : it) {
                        Object value = o.get(key);
                        if (value == null || "".equals(value)) o.put(key, def);
                    }
                }
            }
        }
        return this;
    }

    public void addData(Model m) {
        this.data.add(m);
    }

    public String toJson() {
        return JsonUtil.toJsonString(this);
    }
}
